package com.xavier.dong.nio.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @author XavierDong
 **/
public class NewIOClient {

    public static void main(String[] args) {


        try {
            SocketChannel socketChannel = SocketChannel.open();

            // 连接
            socketChannel.connect(new InetSocketAddress("localhost", 7001));

            String filename = "/Users/xavierdong/Documents/office/Parallels_Desktop14.0.1.dmg";

            // 得到文件的 Channel

            FileInputStream fileInputStream = new FileInputStream(filename);
            FileChannel fileChannel = fileInputStream.getChannel();

            // 准备发送
            long startTime = System.currentTimeMillis();

            // 在Linux下 一个 transferTo 就可以完成传输
            // 在 Win下 一次调用 transferTo 只能 只能发送 8M，就是分段发送，而且要主要传输的地址
            // transferTo 底层用到了 零传输
            long transferToCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

            System.out.println("发送的总的字节数：" + transferToCount + " 耗时: " + (System.currentTimeMillis() - startTime));

            // 关闭
            fileChannel.close();


        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
